using System;
using System.Collections;
using System.Collections.Generic;
using Flaschengeist.Entities;
using Flaschengeist.Views;
using Svelto.Tasks;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadAudio : MonoBehaviour
	{
		private Dictionary<string, AudioClip> clips;
		private ErrorView errorView;
				
		public LoadAudio()
		{
			clips = new Dictionary<string, AudioClip>();
		}
		
		public void Start()
		{			
			errorView = gameObject.GetComponent<ErrorView>();		
		}
		
		public void Process(World world)
		{		
			try 
			{
				ParallelTasks parallelTasks = new ParallelTasks();
				parallelTasks.onComplete += () => Completed(clips);
				
				foreach (string note in world.Scale) 	
				{
					var url = string.Format("{0}{1}/{2}.wav", Settings.AUDIO_SERVER, world.Genre, note);			
					parallelTasks.Add(DownloadNote(note, url));
				}
				
				clips.Clear();
				TaskRunner.Instance.Run(parallelTasks);
			} 
			catch (Exception ex) 
			{
				errorView.Show(ex);
			}
		}
		
		private IEnumerator DownloadNote(string note, string url)
		{					
			Debug.Log("Start load audio from:" + url);	
						
			var www = new WWW(url);		
			var clip = www.GetAudioClip(false, false, AudioType.WAV);
			
			while(!clip.isReadyToPlay) 
				yield return clip;				
			
			Debug.Log("Finish load audio: " + note + ".wav");
			clips.Add(note, clip);
		}
		
		public event Action<Dictionary<string, AudioClip>> Completed;
	}
}

